import { ref, onMounted, getCurrentInstance, computed } from 'vue';

// 列表滚动行为，与tab相关
export const behavior = (props, emits) => {
	const navHeight = ref(0);
	const topDistance = ref(0);
	
	onMounted(() => {
		const statusBarHeight = getApp().globalData.statusBarHeight;
		const navBarHeight = getApp().globalData.navBarHeight;
		navHeight.value = statusBarHeight + navBarHeight;
	
		// 获取页面实例对象
		const instance = getCurrentInstance()
		const query = uni.createSelectorQuery().in(instance)
		query.select('.tabs-placeholder').boundingClientRect((data) => {
			topDistance.value = data.top;
		}).exec();
	});
	
	// 添加isClickTabs是为了防止执行handleScrollToNav事件时tabs会闪一下
	const isClickTabs = ref(false);
	const tabsStyle = computed(() => {
		if (!isClickTabs.value && (topDistance.value - props.scrollTop <= navHeight.value) && topDistance.value) {
			return { 'position': 'fixed', 'top': navHeight.value + 'px' };
		}
		return {};
	});
	
	// 滚动到导航栏
	const handleScrollToNav = () => {
		emits('scrollTo', topDistance.value - navHeight.value);
		isClickTabs.value = true;
		setTimeout(() => {
			isClickTabs.value = false;
		}, 500);
	}
	
	return { tabsStyle, handleScrollToNav };
}